<?php
namespace Api\Service\Amazon;
use Home\Service\CommonService;

class TitleService extends CommonService{
    protected $reportService   = NULL;
    protected $accountsModel   = NULL;
    protected $reportFileModel = NULL;
    protected $reportType      = NULL;
    protected $options         = NULL;
    protected $reportDir       = NULL;

    public function __construct(){
        $this->reportService   = D('Api/Amazon/Report','Service');
        $this->accountsModel   = D('Api/Amazon/Accounts','Model');
        $this->reportTypeModel = D('Api/Amazon/ReportType','Model');
        $this->reportFileModel = D('Api/Amazon/ReportFile','Model');

        $this->reportDir       = dirname(THINK_PATH) . '/Public/report/';

    }
    /**
     * @param $accountId
     * @param int $reportType
     * @return array|bool
     * 描述：根据帐号ID拉取 Title
     */
    public function getTitle($accountId,$reportType = 8){
        $account = $this->accountsModel->getAccountById($accountId);

        $reportType = $this->reportTypeModel->getReportTypeByID($reportType);
        $params = array();
        $params['ReportType'] = $reportType['report_type'];

        $options = array();
        $options['Merchant']    = $account['merchant_id'];
        $options['Marketplace']    = $account['marketplace_id'];
        $options += $params;
        $this->options[$account['id']] = $options;

        if($reportRequestId = $this->reportService->goRequestReport($account, $options)) {
            $options = array();
            $options['Merchant']    = $account['merchant_id'];
            $options['ReportRequestIdList']    = array('Id'=>array($reportRequestId));

            $fileInfo = $this->reportService->getReportFileList(
                $account,
                $this->reportService->goGetReportRequestList($account, $options),
                $reportType['id']
            );

            list($amazonReportId, $reportFileName) = each($fileInfo);
            $rowLists =$this->analysisReportToGetTitle($reportFileName, $amazonReportId);

            return $rowLists;
        }
        return false;
    }

    /**
     * @param null $fileName
     * @param null $reportId
     * @return array|bool
     * 描述：解析报告来过去 Title
     */
    public function analysisReportToGetTitle($fileName = NULL,$reportId = NULL){
        $reportFile = $this->reportFileModel->getReportFile($fileName, $reportId);
        if(empty($reportFile))return false;

        $reportFilePath = $this->reportDir . $reportFile['report_type_id'] . '/' . $reportFile['account_name']. '/' .$reportFile['file_name'];

        $rowLists = $this->goAnalysisReport(
            $reportFile,
            $reportFilePath
        );

        return $rowLists;
    }

    /**
     * @param $reportFile
     * @param $filePath
     * @return array|bool
     * 描述：解析每一行数据，获取帐号，SKU，Title
     */
    public function goAnalysisReport($reportFile, $filePath){
        if(empty($filePath))return false;

        $this->reportFileModel->updateAnalyzeStatus($reportFile['id']);

        $f = @fopen($filePath, 'r');

        $lists = array();
        $rowLine = 0;
        while(!feof($f)) {
            $rowLine ++;
            $row = fgets($f);
            if(empty($row))continue;

            if(!isset($headers)) {
                $row = $this->reportService->checkIsDecodeBlackReport($reportFile, $row);
                if(!empty($row)) {
                    $rowArr = explode("\t", $row);
                    if(empty($rowArr) || empty($rowArr[0]))continue;
                    $headers = ReportService::trimArray($rowArr);
                    continue;
                }
            }

            $rowArr = explode("\t", $row);
            if(empty($rowArr) || empty($rowArr[0]))continue;

            $list = array();
            foreach($headers as $num => $col) {
                if($col == 'seller-sku') {
                    $list['sku'] = trim($rowArr[$num]);
                    continue;
                }
                $list[preg_replace('/-/','_',$col)] = trim($rowArr[$num]);
            }

//            if(!isset($brotherAccountIds)){
//                $brotherAccountIds = D('Api/Amazon/AccountSite','Model')->getBrotherAccountIds($reportFile['account_id']);
//            }
//            $condition['seller_sku'] = array('EQ',$list['sku']);
//            $condition['account_id'] = array('IN',implode(',',$brotherAccountIds));
//
//            $accountId = D('Api/Amazon/AccountSellerSku','Model')->selectSku($condition);
//            $list['account_id'] = $accountId[0]['account_id'];

            $temp = array();
            $temp['account_id'] = $reportFile['account_id'];
            $temp['seller_sku'] = $list['sku'];
            $temp['title']      = $list['item_name'];
            $temp['asin']      = $list['asin1'];

            $lists[] = $temp;
        }

        fclose($f);
        return $lists;
    }


}